#!/usr/bin/lua

if not pcall(function()

http = require('socket.http')
url = require('socket.url')
http.USERAGENT = "ibus-sogoupycc"
keyFile = '/tmp/.sogoucloud-key'

debug = (arg[2] == 'd')
if debug then arg[2] = nil end

local py, timeout, retry, key = arg[1] or 't', tonumber(arg[2])
py = py:gsub("[^a-z]", '')

if timeout == 0 then timeout = 0.4 end

function refresh_key()
	local ret = http.request('http://web.pinyin.sogou.com/web_ime/patch.php') or ''
	key = ret:match('"(.-)"') or ''
	if #key > 0 then local file = io.open(keyFile, 'w') file:write(key) file:close() end
end

start_time = os.time()
if timeout and timeout > 0 then http.TIMEOUT, retry = timeout + 0, 1 else http.TIMEOUT, retry = 0.3, 7 end

-- get key
local file = io.open(keyFile, 'r')
if file then key = file:read("*line") or '' file:close() end

for attempt = 1, retry do if (not key) or (#key == 0) then http.TIMEOUT = http.TIMEOUT * 1.5 refresh_key() else break end end

function try_convert(tail, tail_len)
	local py_tail = (tail or ''):gsub(' ','')
	tail_len = tail_len or 0
	if timeout and timeout > 0 then http.TIMEOUT, retry = timeout + 0, 1 else http.TIMEOUT, retry = 0.3, 20 end
	for attempt = 1, retry do
		if debug then print(attempt, http.TIMEOUT ) end
		local ret = http.request('http://web.pinyin.sogou.com/api/py?key='..key..'&query='..py..py_tail)
		local res = ret and ret:match('ime_callback%("(.-)"')
		if res then
			local content = url.unescape(res)
			local first_word = content:match('(.-)：')
			if first_word and #first_word > 2 then
				io.write(first_word:sub(1, #first_word - 3 * tail_len), '\n')
				for word in content:gmatch('+(.-)：') do
					io.write(word, '\n')
				end
				return 1
			else
				-- not a valid return (still HTTP200 could happen (started in Mar 19 2010, annoying!))
				return 2
			end
		end
		http.TIMEOUT = http.TIMEOUT * 1.8
		if timeout and timeout < 0 and os.time() - start_time > -timeout then
			-- force quit
			io.write('\n')
			return 4
		end
		if http.TIMEOUT > 18 then break end
	end
	return 3
end

-- try various tails
for _, v in pairs{{'', 0}, {'ne', 1}, {'a', 1}, {'le', 1}, {'ma', 1}, {'zhe', 1}, {'na', 1}, {'zhe yang de', 3}, {'zhen de ma', 3}, {'ting hao de', 3}, {'shui xiang xin', 3}, {'zhe shi zhen de ma', 5}, {'na shi bu ke neng de', 6}, {'ni zhi dao ma', 4}, {'ni bu zhi dao', 4}, {'bie wang le a', 4}} do
	local r = try_convert(v[1], v[2])
	if debug then print(v[1], 'result:', r) end
	if r == 3 then break end -- timeout, network problem
	if r == 1 then return end -- success
	if r == 4 then return end -- global timeout
	-- if r == 2, just go on retrying...
end

-- write smth to keep the pipe open, an ampty line indicates retrieve failure
io.write('\n')

-- mark key as invalid (delete it)
os.remove(keyFile)

end) then io.write('\n') end -- error in big pcall

-- ibus-sogoupycc-fetcher-end --
